Navigation & File System
Current Directory & Moving Around
bash
1pwd # Print current working directory2cd /path/to/dir # Change directory3cd ~ # Go to home directory4cd - # Go to previous directory5cd .. # Go up one level6pushd /path # Push directory onto stack and cd7popd # Pop directory from stack and cd backListing Files
bash
1ls # List files2ls -la # List all files (including hidden) with details3ls -lh # Human-readable file sizes4ls -lt # Sort by modification time (newest first)5ls -lS # Sort by size (largest first)6ls -R # List recursively7ls -i # Show inode numbers8tree # Show directory tree (install: sudo apt install tree)9tree -L 2 # Limit tree depth to 2 levelsFinding Files
bash
1find . -name "*.log" # Find files by name2find . -iname "*.txt" # Case-insensitive search3find / -type f -size +100M # Files larger than 100 MB4find . -type f -mtime -7 # Modified in last 7 days5find . -type f -empty # Find empty files6find . -type f -ls # Detailed listing of found files7find . -name "*.tmp" -delete # Find and delete8locate filename # Fast search (uses index, run sudo updatedb first)9which command # Show full path of a command10whereis command # Locate binary, source, man page11type command # Show how a command would be interpretedFile Operations
Create, Copy, Move, Delete
bash
1touch file.txt # Create empty file / update timestamp2mkdir dirname # Create directory3mkdir -p path/to/nested # Create nested directories4cp file.txt copy.txt # Copy file5cp -r dir/ dir_copy/ # Copy directory recursively6mv old.txt new.txt # Rename / move file7rm file.txt # Delete file8rm -rf directory/ # Delete directory recursively (use with caution!)9rmdir empty_dir # Remove empty directory onlyLinking
bash
1ln file hardlink # Create hard link2ln -s /path/to/file symlink # Create symbolic (soft) link3readlink -f symlink # Resolve full path of a symlinkFile Content
bash
1cat file.txt # Print entire file2less file.txt # Scrollable viewer (q to quit)3head -n 20 file.txt # First 20 lines4tail -n 20 file.txt # Last 20 lines5tail -f /var/log/syslog # Follow file in real-time (great for logs)6wc -l file.txt # Count lines7wc -w file.txt # Count words8diff file1 file2 # Compare two files9stat file.txt # Detailed file metadata10file unknown_file # Detect file typeArchiving & Compression
bash
1tar -czf archive.tar.gz dir/ # Create gzipped tar2tar -xzf archive.tar.gz # Extract gzipped tar3tar -xzf archive.tar.gz -C /dest/ # Extract to specific directory4tar -tf archive.tar.gz # List contents without extracting5zip -r archive.zip dir/ # Create zip6unzip archive.zip # Extract zip7gzip file # Compress (replaces original)8gunzip file.gz # DecompressPermissions & Ownership
Viewing Permissions
bash
1ls -la # View permissions2stat -c '%A %a %n' file.txt # Octal + symbolic permissions3getfacl file.txt # View Access Control ListsChanging Permissions
bash
1chmod 755 file.txt # rwxr-xr-x2chmod 644 file.txt # rw-r--r--3chmod +x script.sh # Add execute permission4chmod -R 755 directory/ # Recursive permission changePermission Reference
r=4 w=2 x=1 — Owner / Group / Others. Example: 755 = owner rwx, group r-x, others r-x.
Changing Ownership
bash
1chown user file.txt # Change owner2chown user:group file.txt # Change owner and group3chown -R user:group directory/ # Recursive ownership changeACLs (Access Control Lists)
bash
1setfacl -m u:username:rwx file # Grant user specific access2getfacl -R /some/path > perms.txt # Backup ACLs3setfacl --restore=perms.txt # Restore ACLsText Processing & Search
grep — Search Inside Files
bash
1grep "pattern" file.txt # Search for pattern2grep -i "pattern" file.txt # Case-insensitive3grep -r "pattern" /path/ # Recursive search4grep -n "pattern" file.txt # Show line numbers5grep -c "pattern" file.txt # Count matches6grep -v "pattern" file.txt # Invert match (lines NOT matching)7grep -l "pattern" *.log # List filenames with matches8grep -E "foo|bar" file.txt # Extended regex (egrep)sed — Stream Editor
bash
1sed 's/old/new/' file.txt # Replace first occurrence per line2sed 's/old/new/g' file.txt # Replace all occurrences3sed -i 's/old/new/g' file.txt # In-place edit4sed -n '10,20p' file.txt # Print lines 10-205sed '/pattern/d' file.txt # Delete lines matching patternawk — Column Processing
bash
1awk '{print $1}' file.txt # Print first column2awk '{print $1, $3}' file.txt # Print 1st and 3rd columns3awk -F: '{print $1}' /etc/passwd # Use : as delimiter4awk '{x += $3} END {print x}' file # Sum values in column 35awk 'NR==5,NR==10' file.txt # Print lines 5 to 10Other Useful Text Tools
bash
1sort file.txt # Sort lines alphabetically2sort -n file.txt # Sort numerically3sort -u file.txt # Sort and remove duplicates4uniq # Remove adjacent duplicates (use with sort)5cut -d: -f1 /etc/passwd # Cut fields by delimiter6tr 'a-z' 'A-Z' < file.txt # Translate characters (lowercase → uppercase)7tee output.txt # Read stdin, write to file AND stdout8xargs # Build commands from stdinUser & Group Management
User Operations
bash
1whoami # Current username2id # Current user UID, GID, groups3id username # Info about specific user4sudo adduser username # Create new user (interactive)5sudo useradd username # Create user (non-interactive)6sudo passwd username # Set/change password7sudo deluser username # Delete user8sudo deluser --remove-home user # Delete user + home directory9su - username # Switch to another user10sudo -i # Open root shellGroup Operations
bash
1groups # List groups for current user2groups username # List groups for a user3sudo addgroup groupname # Create group4sudo adduser username groupname # Add user to group5sudo deluser username groupname # Remove user from group6sudo usermod -aG group username # Append user to group (keeps existing)Key User Files
bash
1cat /etc/passwd # All user accounts2cat /etc/group # All groups3cat /etc/shadow # Password hashes (root only)4cat /etc/sudoers # Sudoers config (edit with visudo!)Process Management
Viewing Processes
bash
1ps aux # All running processes2ps aux | grep nginx # Find specific process3top # Real-time process monitor4htop # Better interactive process monitor (install: sudo apt install htop)5pgrep -a nginx # Find PID by name6pidof nginx # Get PID of a running programControlling Processes
bash
1kill PID # Terminate process (SIGTERM)2kill -9 PID # Force kill (SIGKILL)3pkill process_name # Kill by name4killall process_name # Kill all instances by nameBackground & Job Control
bash
1command & # Run in background2jobs # List background jobs3fg %1 # Bring job 1 to foreground4bg %1 # Resume job 1 in background5nohup command & # Run command immune to hangups6disown %1 # Detach job from terminalResource Usage
bash
1free -h # Memory usage2uptime # System uptime and load averages3vmstat 1 # Virtual memory stats (every 1 sec)4iostat 1 # CPU and I/O stats5lsof -p PID # Files opened by a process6lsof -i :80 # What process is using port 80Disk & Storage
Disk Usage
bash
1df -h # Filesystem disk space usage2df -i # Inode usage3du -sh /path # Total size of a directory4du -sh * # Size of each item in current dir5du -h --max-depth=1 # One level deep summary6ncdu / # Interactive disk usage browser (install: sudo apt install ncdu)Disk & Partitions
bash
1lsblk # List block devices (disks, partitions)2blkid # Show UUID and filesystem type3fdisk -l # List partition tables4mount # Show mounted filesystems5mount /dev/sdb1 /mnt/data # Mount a partition6umount /mnt/data # Unmount7cat /etc/fstab # Permanent mount configurationPackage Management (APT)
Basic APT Commands
bash
1sudo apt update # Refresh package index2sudo apt upgrade # Upgrade all installed packages3sudo apt full-upgrade # Upgrade with dependency changes4sudo apt install package_name # Install a package5sudo apt remove package_name # Remove a package (keep config)6sudo apt purge package_name # Remove package + config files7sudo apt autoremove # Remove unneeded dependencies8sudo apt search keyword # Search for packages9sudo apt show package_name # Show package details10sudo apt list --installed # List all installed packages11sudo apt list --upgradable # List upgradable packagesDPKG (Low-Level)
bash
1dpkg -l # List all installed packages2dpkg -l | grep package # Check if a package is installed3dpkg -S /path/to/file # Which package owns this file?4dpkg -i package.deb # Install local .deb file5dpkg --configure -a # Configure partially installed packages6dpkg --audit # List problematic packagesAPT Repositories
bash
1cat /etc/apt/sources.list # Main repo config2ls /etc/apt/sources.list.d/ # Additional repo configs3sudo add-apt-repository ppa:name/ppa # Add PPA4sudo add-apt-repository --remove ppa:name/ppa # Remove PPASnap Packages
bash
1snap list # List installed snaps2sudo snap install package # Install snap3sudo snap remove package # Remove snap4sudo snap refresh # Update all snaps5snap info package # Snap detailsNetworking
IP & Interfaces
bash
1ip addr show # Show IP addresses (modern)2ip link show # Show network interfaces3ip route show # Show routing table / default gateway4hostname -I # Quick way to get local IP5ifconfig # Legacy IP info (net-tools)Connectivity Testing
bash
1ping -c 4 google.com # Ping with 4 packets2traceroute google.com # Trace route to host3mtr google.com # Combined ping + traceroute4curl -I https://example.com # Fetch HTTP headers5wget https://example.com/file.tar.gz # Download fileDNS
bash
1dig example.com # DNS lookup2dig +short example.com # Short DNS answer3nslookup example.com # Legacy DNS lookup4host example.com # Simple DNS lookup5cat /etc/resolv.conf # DNS resolver configuration6resolvectl status # systemd-resolved DNS statusPorts & Connections
bash
1ss -tulnp # List listening ports (modern)2ss -plat # All TCP connections with processes3netstat -tulnp # Legacy listening ports4lsof -iTCP -sTCP:LISTEN -P -n # Listening TCP processes5nmap -sT localhost # Port scan (install: sudo apt install nmap)Firewall (UFW)
bash
1sudo ufw status # Show firewall status2sudo ufw enable # Enable firewall3sudo ufw disable # Disable firewall4sudo ufw allow 22/tcp # Allow SSH5sudo ufw allow 80/tcp # Allow HTTP6sudo ufw allow 443/tcp # Allow HTTPS7sudo ufw deny 3306 # Block MySQL port8sudo ufw delete allow 80/tcp # Remove a rule9sudo ufw logging on # Enable logging10sudo ufw reset # Reset all rulesNetplan (Ubuntu Network Config)
bash
1ls /etc/netplan/ # Netplan config files2cat /etc/netplan/*.yaml # View network config3sudo netplan apply # Apply network changes4sudo netplan try # Test config (auto-reverts on failure)Systemd & Services
Service Management
bash
1sudo systemctl start service # Start a service2sudo systemctl stop service # Stop a service3sudo systemctl restart service # Restart a service4sudo systemctl reload service # Reload config without restart5sudo systemctl status service # Check service status6sudo systemctl enable service # Enable on boot7sudo systemctl disable service # Disable on boot8sudo systemctl is-active service # Check if active9sudo systemctl is-enabled service # Check if enabled on bootListing & Inspecting
bash
1systemctl list-units --type=service # List running services2systemctl list-units --type=service --all # List all services3systemctl list-unit-files # List unit files (enabled/disabled)4systemctl cat service # Show unit file content5systemctl show service # Show all propertiesSystem Control
bash
1sudo systemctl daemon-reload # Reload unit files after changes2sudo systemctl poweroff # Shutdown3sudo systemctl reboot # Reboot4sudo systemctl suspend # Suspend5sudo systemctl hibernate # HibernateTimers (Cron Alternative)
bash
1systemctl list-timers # List active timers2systemctl status snap.certbot.renew.timer # Timer status exampleLogs & Journalctl
Journalctl (systemd logs)
bash
1journalctl # All logs2journalctl -u nginx # Logs for specific service3journalctl -u nginx --since today # Since today4journalctl -u nginx --since "1 hour ago"5journalctl -f # Follow logs in real-time6journalctl -p err # Only errors7journalctl -p warning # Warnings and above8journalctl --disk-usage # Log storage size9journalctl -b # Logs from current boot10journalctl -b -1 # Logs from previous boot11journalctl --list-boots # List all boot sessionsTraditional Log Files
bash
1# Most logs are in /var/log/2ls /var/log/3
4# Key log files:5cat /var/log/syslog # General system log6cat /var/log/auth.log # Authentication & sudo logs7cat /var/log/kern.log # Kernel messages8cat /var/log/dpkg.log # Package manager log9cat /var/log/apt/history.log # APT install history10cat /var/log/boot.log # Boot messages11cat /var/log/ufw.log # Firewall log (if UFW enabled)12
13# Nginx / Apache logs:14cat /var/log/nginx/access.log15cat /var/log/nginx/error.log16cat /var/log/apache2/access.log17cat /var/log/apache2/error.log18
19# MySQL / MariaDB:20cat /var/log/mysql/error.log21
22# Follow logs in real-time:23tail -f /var/log/syslogdmesg (Kernel Ring Buffer)
bash
1dmesg # All kernel messages2dmesg | tail -20 # Last 20 kernel messages3dmesg -T # Human-readable timestamps4dmesg --level=err # Only errors5dmesg -w # Follow in real-timeImportant Config File Locations
Quick reference for where Ubuntu stores key configuration files:
System
| File / Directory | Purpose |
|---|---|
/etc/hostname | System hostname |
/etc/hosts | Static host-to-IP mappings |
/etc/fstab | Filesystem mount table |
/etc/environment | System-wide environment variables |
/etc/timezone | Timezone setting |
/etc/locale.gen | Locale configuration |
/etc/default/grub | GRUB bootloader config |
/etc/crontab | System-wide cron jobs |
/etc/sysctl.conf | Kernel parameters |
Networking
| File / Directory | Purpose |
|---|---|
/etc/netplan/*.yaml | Network config (Ubuntu 18.04+) |
/etc/resolv.conf | DNS resolver |
/etc/hosts.allow | TCP wrappers allow |
/etc/hosts.deny | TCP wrappers deny |
Security & Users
| File / Directory | Purpose |
|---|---|
/etc/passwd | User accounts |
/etc/shadow | Password hashes |
/etc/group | Group definitions |
/etc/sudoers | Sudo access (edit with visudo) |
/etc/ssh/sshd_config | SSH server config |
/etc/pam.d/ | PAM authentication modules |
Services
| File / Directory | Purpose |
|---|---|
/etc/nginx/ | Nginx config |
/etc/apache2/ | Apache config |
/etc/mysql/ | MySQL / MariaDB config |
/etc/docker/daemon.json | Docker daemon config |
/etc/systemd/system/ | Custom systemd unit files |
Package Management
| File / Directory | Purpose |
|---|---|
/etc/apt/sources.list | APT repositories |
/etc/apt/sources.list.d/ | Additional repos |
/etc/apt/apt.conf.d/ | APT configuration fragments |
Shell
| File / Directory | Purpose |
|---|---|
~/.bashrc | Per-user Bash config (interactive) |
~/.bash_profile | Per-user login shell config |
~/.profile | Per-user profile (used by many shells) |
/etc/bash.bashrc | System-wide Bash config |
/etc/profile | System-wide login shell profile |
/etc/profile.d/ | Drop-in profile scripts |
SSH
Connecting
bash
1ssh user@host # Connect to remote host2ssh -p 2222 user@host # Custom port3ssh -i ~/.ssh/key.pem user@host # Specify private key4ssh -L 8080:localhost:80 user@host # Local port forwarding5ssh -J jumphost user@target # Jump through bastion hostKey Management
bash
1ssh-keygen -t ed25519 -C "[email protected]" # Generate key pair2ssh-copy-id user@host # Copy public key to server3cat ~/.ssh/authorized_keys # View authorized keys4eval "$(ssh-agent -s)" && ssh-add ~/.ssh/key # Start agent & add keySSH Config File
bash
1cat ~/.ssh/config # Per-user SSH configExample ~/.ssh/config:
text
1Host myserver2 HostName 192.168.1.1003 User admin4 Port 225 IdentityFile ~/.ssh/mykeyCron & Scheduled Tasks
Crontab
bash
1crontab -e # Edit current user's crontab2crontab -l # List current crontab3crontab -r # Remove current crontab4sudo crontab -u user -e # Edit another user's crontabCron Syntax
text
1# ┌───────────── minute (0–59)2# │ ┌───────────── hour (0–23)3# │ │ ┌───────────── day of month (1–31)4# │ │ │ ┌───────────── month (1–12)5# │ │ │ │ ┌───────────── day of week (0–7, 0 & 7 = Sunday)6# │ │ │ │ │7# * * * * * command_to_run8
9# Examples:100 2 * * * /usr/local/bin/backup.sh # Daily at 2:00 AM11*/15 * * * * /usr/bin/check-health.sh # Every 15 minutes120 0 * * 0 /usr/local/bin/weekly.sh # Weekly on Sunday midnight13@reboot /usr/local/bin/on-startup.sh # Run at bootCron Directories (Drop-In Scripts)
bash
1ls /etc/cron.d/ # Custom cron files2ls /etc/cron.daily/ # Runs daily3ls /etc/cron.hourly/ # Runs hourly4ls /etc/cron.weekly/ # Runs weekly5ls /etc/cron.monthly/ # Runs monthlySystem Information
Hardware & OS
bash
1uname -a # Kernel & OS info2lsb_release -a # Ubuntu version details3cat /etc/os-release # OS release info4hostnamectl # Hostname and OS details5arch # CPU architecture6lscpu # CPU info7lsmem # Memory info8lspci # PCI devices9lsusb # USB devices10lshw -short # Full hardware summary11dmidecode -t memory # Detailed RAM info (root)System Resources
bash
1free -h # Memory usage2uptime # Uptime & load3cat /proc/cpuinfo # CPU details4cat /proc/meminfo # Memory details5nproc # Number of CPU coresDate & Time
bash
1date # Current date/time2timedatectl # Timezone & NTP status3sudo timedatectl set-timezone America/New_York # Set timezoneEnvironment Variables
bash
1env # List all environment variables2echo $PATH # Print specific variable3echo $HOME # Home directory4export VAR="value" # Set variable for current session5printenv VAR # Print variable valueMaking Variables Persistent
bash
1# For current user — add to ~/.bashrc:2echo 'export MY_VAR="value"' >> ~/.bashrc3source ~/.bashrc4
5# System-wide — add to /etc/environment:6sudo nano /etc/environment7# Add: MY_VAR="value"Useful One-Liners & Tips
History
bash
1history # Show command history2history | grep ssh # Search history3!! # Repeat last command4!$ # Last argument of previous command5ctrl+r # Reverse search in historyPiping & Redirection
bash
1command > file.txt # Redirect stdout to file (overwrite)2command >> file.txt # Append stdout to file3command 2> error.log # Redirect stderr4command &> all.log # Redirect both stdout and stderr5command1 | command2 # Pipe stdout to next command6command | tee file.txt # Pipe and save to file simultaneouslyHandy Shortcuts
bash
1ctrl+c # Cancel current command2ctrl+z # Suspend current command3ctrl+d # Logout / end input4ctrl+l # Clear screen5ctrl+a # Move cursor to beginning of line6ctrl+e # Move cursor to end of line7ctrl+w # Delete word before cursor8ctrl+u # Delete from cursor to beginning of line9ctrl+k # Delete from cursor to end of line10tab # Auto-completeQuick Operations
bash
1alias ll='ls -la' # Create an alias2sudo !! # Run last command as sudo3watch -n 5 'df -h' # Repeat command every 5 seconds4time command # Measure execution time5yes | command # Auto-confirm prompts6command1 && command2 # Run command2 only if command1 succeeds7command1 || command2 # Run command2 only if command1 fails